/**
 * Copyright (C), 2015-2019, XXX有限公司
 * FileName: WechatController
 * Author:   xi
 * Date:     2019/8/16 16:53
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.supconit.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.supconit.entity.User;
import com.supconit.entity.WxTicket;
import com.supconit.service.IUserService;
import com.supconit.util.CookieConstant;
import com.supconit.util.RedisUtils;
import com.supconit.util.WX_TokenUtil;
import com.supconit.util.WeixinUtil;
import io.netty.util.internal.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 〈一句话功能简述〉<br> 
 * 〈〉
 *
 * @author xi
 * @create 2019/8/16
 * @since 1.0.0
 */
@RestController
@RequestMapping("/wechat")
public class WechatController {

    private static final Logger logger = LoggerFactory.getLogger(WechatController.class);

    @Value("${wechat.appId}")
    private String appId;

    @Value("${wechat.appSecret}")
    private String appSecret;

    @Value("${wechat.appId2}")
    private String appId2;

    @Value("${wechat.appSecret2}")
    private String appSecret2;

    @Autowired
    private IUserService userService;

    @Autowired
    RedisUtils redisUtils;
    /**
     *保存求助信息
     */
    @ResponseBody
    @RequestMapping(value = "getWxInfo", method = RequestMethod.POST)
    public Object getWxInfo(String code) {
        JSONObject wxInfo = WeixinUtil.getWxInfo(appId2, appSecret2,code);
        String openId = wxInfo.getString(CookieConstant.OPENID);
        String token = redisUtils.get("token2");
        if(StringUtil.isNullOrEmpty(token)){
            token =  WeixinUtil.getToken(appId2, appSecret2);
            redisUtils.set("token2",token,7200);
        }
//        String token =  WeixinUtil.getToken(appId2, appSecret2);
        logger.info(openId);
        logger.info(token);
        JSONObject userInfo = WeixinUtil.getUserInfo2(openId, token);
        // 获取当前的Unionid
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(User::getFlag,0);
        String unionid =userInfo.getString("unionid");
        if(!StringUtils.isEmpty(unionid)){
            wrapper.lambda().eq(User::getUnionid,unionid);
            // 根据UnionId获取当前的openId
            List<User> lst = userService.list(wrapper);
            if(lst!=null && lst.size()==1){
                User user = lst.get(0);
                String token2 =  WeixinUtil.getToken(appId, appSecret);
                JSONObject userInfo2 = WeixinUtil.getUserInfo2(user.getOpenId(), token2);
                return userInfo2;
            }
        }
        return null;
    }

    /**
     *获取TICKET
     */
    @ResponseBody
    @RequestMapping(value = "getTicket", method = RequestMethod.POST)
    public Object getTicket(String url) {

        WxTicket ticket = WX_TokenUtil.getTicket(appId, appSecret, url);

        return ticket;
    }

//
    @ResponseBody
    @RequestMapping(value = "test", method = RequestMethod.POST)
    public Object test() {
        String token ="";

        token =  WeixinUtil.getToken(appId, appSecret);
        JSONObject obj =WeixinUtil.getOpenIds(token, "");
        logger.info(obj.toString());
        String data = obj.getString("data");
        JSONObject jsonObject=JSONObject.parseObject(data);
        JSONArray openIds = jsonObject.getJSONArray("openId");
        String count = jsonObject.getString("count");
        // 批量根据openId 获取unionid
        String nextOpenId =  obj.getString("next_openid");
        return obj;
    }


//    /**
//     *保存求助信息
//     */
//    @ResponseBody
//    @RequestMapping(value = "getUserInfo", method = RequestMethod.POST)
//    public Object getUserInfo(String openId,String token,String fresh_token) {
//
//        if(!StringUtils.isEmpty(fresh_token)){
//            token =  WeixinUtil.refreshToken(appId, fresh_token);
//        }
//        JSONObject userInfo = WeixinUtil.getUserInfo2(openId, token);
//
//        return userInfo;
//    }
}